package com.uploadfile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pojo.Image;
import com.service.UploadService;
import com.service.impl.UploadServiceImpl;

@WebServlet("/download")
public class DownloadFile extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String name = request.getParameter("username");
	
		UploadService uploadService = new UploadServiceImpl();
		
		String pictureFile = uploadService.selectImageByName(name);
		
		String fileName = pictureFile.substring(pictureFile.lastIndexOf("/"));
 
		response.setContentType("application/octet-stream");

		String string = fileName.substring(fileName.lastIndexOf("/"));
		String substring = string.substring(1, string.length());
		//  下载必须设置头
		response.setHeader("content-disposition", "attachment;filename="+substring);
 
		//String path = getServletContext().getRealPath("/upload");
		String path = "E:\\pic\\";
		File file = new File(path,fileName);
        //  获得文件
        InputStream is = new FileInputStream(file);
 
        //  输出流
        OutputStream os = response.getOutputStream();
 
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=is.read(buffer))!=-1) {
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
        
       // response.sendRedirect(request.getContextPath()+"/ListServlet");
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
